import {
  Column,
  Entity,
  PrimaryGeneratedColumn,
  ManyToMany,
  OneToMany,
  BeforeInsert,
} from 'typeorm';
import { User } from '../../users/entities/user.entity';
import { JoinTable } from 'typeorm';
import { Permission } from '../../permission/entities/permission.entity';
import RoleEnum from './RoleEnum';

@Entity()
export class Role {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  // 角色可以有多个权限
  @ManyToMany(() => Permission, (permission) => permission.roles, {
    nullable: true,
  })
  @JoinTable({
    name: 'role_permissions', // 指定中间表的名称
    joinColumn: {
      name: 'roleId',
      referencedColumnName: 'id',
    },
    inverseJoinColumn: {
      name: 'permissionId',
      referencedColumnName: 'id',
    },
  })
  permissions?: Permission[];

  // 角色可以被多个用户拥有
  @OneToMany(() => User, (user) => user.role, { cascade: true, nullable: true })
  @JoinTable({
    name: 'user_roles', // 指定中间表的名称
    joinColumn: {
      name: 'roleId',
      referencedColumnName: 'id',
    },
    inverseJoinColumn: {
      name: 'userId',
      referencedColumnName: 'id',
    },
  })
  users: User[];

  @Column({
    type: 'varchar',
    length: 32,
    comment: '角色名',
    default: RoleEnum.Anonymous,
    unique: true,
  })
  roleName: string;

  @Column({
    type: 'varchar',
    length: 255,
    comment: '角色代码',
    default: 'Anonymous',
  })
  roleCode: string;

  @Column({
    type: 'integer',
    comment: '角色级别',
    default: 0,
  })
  roleLevel: number;

  @Column({
    type: 'datetime',
    default: () => 'CURRENT_TIMESTAMP',
    comment: '创建时间',
  })
  create_time: Date;

  @Column({
    type: 'datetime',
    default: () => 'CURRENT_TIMESTAMP',
    onUpdate: 'CURRENT_TIMESTAMP',
    comment: '更新时间',
  })
  update_time: Date;

  @Column({ type: 'boolean', comment: '是否禁用', default: false })
  is_disabled: boolean;

  @Column({ type: 'boolean', comment: '是否删除', default: false })
  is_deleted: boolean;

  @Column({ type: 'datetime', comment: '禁用时间', default: null })
  disabled_time: Date;

  @Column({ type: 'datetime', comment: '删除时间', default: null })
  delete_time: Date;
}
